package com.tin.triper.UI;

import java.io.File;
import java.util.Date;

import com.tin.triper.Constants;
import com.tin.triper.R;
import com.tin.triper.Data.LocationProvider;

import android.app.Activity;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class VoiceActivity extends Activity {
	EditText editTextDescription;
	TextView textViewDescription;
	Button buttonOK;
	Button buttonCancel;
	Button buttonErase;
	Button buttonRecord;
	Button buttonPlay;
	SharedPreferences prefs;
	boolean recording = false;
	boolean recorded = false;
	boolean playing = false;
	String fileName = "";
	private MediaRecorder mRecorder = null;
	private MediaPlayer mPlayer = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		prefs = getSharedPreferences(Constants.PREFS_NAME, MODE_PRIVATE);

		if (getIntent().getExtras().getInt(Constants.ACTIVITY_MODE) == 0) {
			// add
			setContentView(R.layout.voice_add);
			Date date = new Date();
			fileName = "Voice_" + date.getTime() + ".mp4";
			editTextDescription = (EditText) findViewById(R.id.voice_add_description_field);
			buttonOK = (Button) findViewById(R.id.voice_add_button_ok);
			buttonCancel = (Button) findViewById(R.id.voice_add_button_cancel);
			buttonRecord = (Button) findViewById(R.id.voice_record_button);
			File mediaStorageDir = new File(Environment
					.getExternalStorageDirectory().getAbsolutePath()
					+ "/"
					+ Constants.APP_FOLDER_NAME
					+ "/"
					+ prefs.getInt(Constants.RECORDED_TRIP_ID, 0)
					+ " "
					+ prefs.getString(Constants.RECRODED_TRIP_NAME, "")
					+ "/Voice/");
			if (!mediaStorageDir.exists()) {
				if (!mediaStorageDir.mkdirs()) {
					return;
				}
			}
			buttonRecord.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					Button bt = (Button) view;
					if (recording) {
						stopRecording();
						bt.setText(getString(R.string.common_record));
					} else {
						startRecording(fileName, prefs.getInt(
								Constants.RECORDED_TRIP_ID, 0), prefs
								.getString(Constants.RECRODED_TRIP_NAME, ""));
						bt.setText(getString(R.string.common_stop));
					}
				}
			});
			buttonOK.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					if (recorded
							&& !editTextDescription.getText().toString()
									.equals("")) {
						ContentValues values = new ContentValues();
						values.put(LocationProvider.RESOURCE_FILENAME, fileName);
						values.put(LocationProvider.RESOURCE_TYPE, 1);// TODO
																		// add
																		// enum
						values.put(LocationProvider.RESOURCE_DESCRIPTION,
								editTextDescription.getText().toString());
						values.put(LocationProvider.TRIP_ID,
								prefs.getInt(Constants.RECORDED_TRIP_ID, 0));
						values.put(LocationProvider.LOCATION_ID, prefs.getInt(
								Constants.LAST_INSERTED_LOCATION_ID, 0));
						getContentResolver().insert(
								LocationProvider.CONTENT_URI_RESOURCES, values);
						finish();
					} else {
						if (!recorded) {
							Toast.makeText(
									VoiceActivity.this,
									getString(R.string.error_message_no_file_recorded),
									Toast.LENGTH_SHORT).show();
						}
						if (editTextDescription.getText().toString().equals("")) {
							Toast.makeText(
									VoiceActivity.this,
									getString(R.string.error_message_no_description),
									Toast.LENGTH_SHORT).show();
						}
					}
				}
			});
			buttonCancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					setResult(Constants.VOICE_ACTIVITY);
					finish();
				}
			});
		} else if (getIntent().getExtras().getInt(Constants.ACTIVITY_MODE) == 1) {
			// edit
			setContentView(R.layout.voice_edit);
			editTextDescription = (EditText) findViewById(R.id.voice_edit_description_field);
			buttonOK = (Button) findViewById(R.id.voice_edit_button_ok);
			buttonCancel = (Button) findViewById(R.id.voice_edit_button_cancel);
			buttonPlay = (Button) findViewById(R.id.voice_record_button);

			Cursor cursor = getContentResolver().query(
					LocationProvider.CONTENT_URI_RESOURCES,
					new String[] { LocationProvider.RESOURCE_DESCRIPTION,
							LocationProvider.RESOURCE_FILENAME },
					LocationProvider.RESOURCE_ID
							+ " ='"
							+ getIntent().getExtras().getInt(
									Constants.RESOURCE_ID) + "'", null, null);
			if (cursor != null)
				if (cursor.moveToFirst()) {
					editTextDescription.setText(cursor.getString(0));
					fileName = cursor.getString(1);
				}
			cursor.close();

			buttonOK.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					if (!editTextDescription.getText().toString().equals("")) {
						ContentValues values = new ContentValues();
						values.put(LocationProvider.RESOURCE_DESCRIPTION,
								editTextDescription.getText().toString());
						getContentResolver().update(
								LocationProvider.CONTENT_URI_RESOURCES,
								values,
								LocationProvider.RESOURCE_ID
										+ " ='"
										+ getIntent().getExtras().getInt(
												Constants.RESOURCE_ID) + "'",
								null);
						finish();
					} else {
						Toast.makeText(
								VoiceActivity.this,
								getString(R.string.error_message_no_description),
								Toast.LENGTH_SHORT).show();
					}
				}
			});
			buttonPlay.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Button bt = (Button) v;
					if (playing) {
						stopPlaying();
						bt.setText(getString(R.string.common_stop));
					} else {
						startPlaying(
								fileName,
								getIntent().getExtras().getInt(
										Constants.TRIP_ID),
								getIntent().getExtras().getString(
										Constants.TRIP_NAME));
						bt.setText(getString(R.string.common_play));
					}
				}
			});
			buttonCancel.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					finish();
				}
			});

		} else if (getIntent().getExtras().getInt(Constants.ACTIVITY_MODE) == 2) {
			// view
			setContentView(R.layout.voice_view);
			textViewDescription = (TextView) findViewById(R.id.voice_view_description_field);
			buttonOK = (Button) findViewById(R.id.voice_view_button_ok);
			buttonPlay = (Button) findViewById(R.id.voice_record_button);

			Cursor cursor = getContentResolver().query(
					LocationProvider.CONTENT_URI_RESOURCES,
					new String[] { LocationProvider.RESOURCE_DESCRIPTION,
							LocationProvider.RESOURCE_FILENAME },
					LocationProvider.RESOURCE_ID
							+ " ='"
							+ getIntent().getExtras().getInt(
									Constants.RESOURCE_ID) + "'", null, null);
			if (cursor != null)
				if (cursor.moveToFirst()) {
					textViewDescription.setText(cursor.getString(0));
					fileName = cursor.getString(1);
				}
			cursor.close();
			buttonOK.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					finish();
				}
			});
			buttonPlay.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Button bt = (Button) v;
					if (playing) {
						stopPlaying();
						bt.setText(getString(R.string.common_stop));
					} else {
						startPlaying(
								fileName,
								getIntent().getExtras().getInt(
										Constants.TRIP_ID),
								getIntent().getExtras().getString(
										Constants.TRIP_NAME));
						bt.setText(getString(R.string.common_play));
					}
				}
			});
		}
	}

	private void startRecording(String fileName, int tripId, String tripName) {
		mRecorder = new MediaRecorder();
		mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
		mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
		mRecorder.setOutputFile(Environment.getExternalStorageDirectory()
				.getAbsolutePath()
				+ "/"
				+ Constants.APP_FOLDER_NAME
				+ "/"
				+ tripId + " " + tripName + "/Voice/" + fileName);
		mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		try {
			mRecorder.prepare();
			recording = true;
		} catch (Exception e) {
			recording = false;
			Toast.makeText(VoiceActivity.this,
					getString(R.string.error_message_record_start_failed),
					Toast.LENGTH_SHORT).show();
		}

		mRecorder.start();

	}

	private void stopRecording() {
		mRecorder.stop();
		mRecorder.release();
		recorded = true;
		recording = false;
		mRecorder = null;

	}

	private void startPlaying(String fileName, int tripId, String tripName) {
		mPlayer = new MediaPlayer();
		try {
			mPlayer.setDataSource(Environment.getExternalStorageDirectory()
					.getAbsolutePath()
					+ "/"
					+ Constants.APP_FOLDER_NAME
					+ "/"
					+ tripId + " " + tripName + "/Voice/" + fileName);
			mPlayer.prepare();
			mPlayer.start();
			playing = true;
		} catch (Exception e) {
			playing = false;
			Toast.makeText(VoiceActivity.this,
					getString(R.string.error_message_player_start_failed),
					Toast.LENGTH_SHORT).show();
		}
	}

	private void stopPlaying() {
		mPlayer.release();
		playing = false;
		mPlayer = null;
	}

}
